package com.linln.component.email;

import com.linln.common.constant.ParamConst;
import com.linln.component.thymeleaf.utility.ParamUtil;
import com.linln.modules.system.repository.MailRepository;
import com.linln.modules.system.repository.ParamRepository;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.TemplateSpec;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;


import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

/**
 * @ProjectName: noteblogv4
 * @Package: me.wuwenbin.noteblogv4.service.mail
 * @ClassName: ${CLASS_NAME}
 * @Author: 林平
 * @CreateDate: 2019-01-23 17:54
 * @Version: 1.0
 * @Copyright: Copyright Reserved (c) 2019, http://www.longshine.com
 * @Dependency:
 * @Description: java类作用描述
 * -
 * ****************************************************************
 * @UpdateUser: 13434
 * @UpdateDate: 2019-01-23 17:54
 * @UpdateRemark: The modified content
 * ****************************************************************
 * -
 */
@Slf4j
@Service
public class MailServiceUtilImpl implements MailServiceUtil {
    private final ParamRepository paramRepository;
    @Autowired
    private TemplateEngine templateEngine;

    @Autowired
    private MailRepository mailRepository;

    @Autowired
    private SpringResourceTemplateResolver springResourceTemplateResolver;
    @Autowired
    public MailServiceUtilImpl(ParamRepository paramRepository) {
        this.paramRepository = paramRepository;
}



    @Override
    public  void sendMsgMail( Email email)
    {
        JavaMailSenderImpl javaMailSender=new JavaMailSenderImpl();

        try{

            String host =  ParamUtil.value(ParamConst.MAIL_SMPT_SERVER_ADDR);
            String port = ParamUtil.value(ParamConst.MAIL_SMPT_SERVER_PORT);
            String from =  ParamUtil.value(ParamConst.MAIL_SERVER_ACCOUNT);
            String user = ParamUtil.value(ParamConst.MAIL_SENDER_NAME);
            String pass =  ParamUtil.value(ParamConst.MAIL_SERVER_PASSWORD);



            javaMailSender.setHost(host); //smtp.126.com
            javaMailSender.setPort(Integer.valueOf(port));
            javaMailSender.setPassword(pass);//对于qq邮箱而言 密码指的就是发送方的授权码
            javaMailSender.setProtocol("smtp");
            javaMailSender.setUsername(user);



            Properties properties = new Properties();
            properties.setProperty("mail.smtp.auth", "true");//开启认证
            properties.setProperty("mail.debug", "true");//启用调试
            properties.setProperty("mail.smtp.timeout", "1000");//设置链接超时
            properties.setProperty("mail.smtp.port", port);//设置端口
            properties.setProperty("mail.smtp.socketFactory.port", port);//设置ssl端口
            properties.setProperty("mail.smtp.socketFactory.fallback", "false");
            properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            javaMailSender.setJavaMailProperties(properties);

            String nick="";
            try {
                nick=javax.mail.internet.MimeUtility.encodeText("小海豚博客系统邮件");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            mimeMessageHelper.setFrom(new InternetAddress(nick+" <"+from+">"));
            mimeMessageHelper.setTo(email.getTo());
            mimeMessageHelper.setSubject(email.getSubject());
            String html = "<html><body><div>"+email.getComment()+"</div></body></html>";
            mimeMessageHelper.setText(html, true);


            javaMailSender.send(mimeMessage);

        } catch (Exception e) {
            log.error("初始化邮件信息失败，错误信息：{}", e.getMessage());
            e.printStackTrace();
            throw new RuntimeException(e);
        }



//        //true表示需要创建一个multipart message
//        MimeMessageHelper helper=new MimeMessageHelper(comment,true);
//        helper.setFrom(form);
//        helper.setTo(form);
//        helper.setSubject(subject);
//        helper.setText(content,true);
//        mailSender.send(message);
//        System.out.println("html格式邮件发送成功");

    }

    public void htmlEmail(Context ctx,Email email) {
        JavaMailSenderImpl javaMailSender=new JavaMailSenderImpl();

        String host =  ParamUtil.value(ParamConst.MAIL_SMPT_SERVER_ADDR);
        String port = ParamUtil.value(ParamConst.MAIL_SMPT_SERVER_PORT);
        String from =  ParamUtil.value(ParamConst.MAIL_SERVER_ACCOUNT);
        String user = ParamUtil.value(ParamConst.MAIL_SENDER_NAME);
        String pass =  ParamUtil.value(ParamConst.MAIL_SERVER_PASSWORD);



       // String to = paramRepository.findFirstByName(ParamConst.MAIL_SERVER_TO).getValue();
        javaMailSender.setDefaultEncoding("UTF-8");
        javaMailSender.setHost(host); //smtp.126.com
        javaMailSender.setPort(Integer.valueOf(port));
        javaMailSender.setPassword(pass);//对于qq邮箱而言 密码指的就是发送方的授权码
        javaMailSender.setProtocol("smtp");
        javaMailSender.setUsername(user);

        Properties properties = new Properties();
        properties.setProperty("mail.smtp.auth", "true");//开启认证
        properties.setProperty("mail.debug", "true");//启用调试
        properties.setProperty("mail.smtp.timeout", "1000");//设置链接超时
        properties.setProperty("mail.smtp.port", port);//设置端口
        properties.setProperty("mail.smtp.socketFactory.port", port);//设置ssl端口
        properties.setProperty("mail.smtp.socketFactory.fallback", "false");
        properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        javaMailSender.setJavaMailProperties(properties);

        String nick="";
        try {
            nick=javax.mail.internet.MimeUtility.encodeText("小海豚博客系统邮件");


        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true);
        message.setFrom(new InternetAddress(nick+" <"+from+">"));
        message.setTo(email.getTo());
        message.setSubject(email.getSubject());

        TemplateSpec templateSpec=new TemplateSpec("e","");
        templateSpec.getTemplate();
        //执行模板引擎，执行模板引擎需要传入模板名、上下文对象
        String emailText = templateEngine.process(email.getTemplate(), ctx);

        message.setText(emailText, true);

        javaMailSender.send(mimeMessage);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void  getMail(){
        String user = ParamUtil.value(ParamConst.MAIL_SENDER_NAME);
        String pass =  ParamUtil.value(ParamConst.MAIL_SERVER_PASSWORD);
        // 准备连接服务器的会话信息
        Properties props = new Properties();
        props.setProperty("mail.store.protocol", "pop3");		// 协议
        props.setProperty("mail.pop3.port", "110");				// 端口
        props.setProperty("mail.pop3.host", "pop3.nonelonely.com");	// pop3服务器

        // 创建Session实例对象
        Session session = Session.getInstance(props);
        Folder folder = null;
        Store store = null;;
        try {
            store = session.getStore("pop3");
            store.connect(user, pass);
            // 获得收件箱
            folder = store.getFolder("INBOX");

            /* Folder.READ_ONLY：只读权限
             * Folder.READ_WRITE：可读可写（可以修改邮件的状态）
             */
            folder.open(Folder.READ_WRITE);	//打开收件箱

            // 由于POP3协议无法获知邮件的状态,所以getUnreadMessageCount得到的是收件箱的邮件总数
            //  System.out.println("未读邮件数: " + folder.getUnreadMessageCount());

            // 由于POP3协议无法获知邮件的状态,所以下面得到的结果始终都是为0
//        System.out.println("删除邮件数: " + folder.getDeletedMessageCount());
//        System.out.println("新邮件: " + folder.getNewMessageCount());
//
//        // 获得收件箱中的邮件总数
//        System.out.println("邮件总数: " + folder.getMessageCount());
            int n = mailRepository.findMessageNumber();
            // 得到收件箱中的所有邮件,并解析
            Message[] messages = folder.getMessages();

            POP3ReceiveMailTest.parseMessage(mailRepository,messages);
        }catch (Exception e){
            log.info(e.getMessage());
        }finally {
            //释放资源
            try {
                folder.close(true);
                store.close();
            }catch (Exception e){
                log.info(e.getMessage());
            }


        }
    }

}
